package thread;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import depot.Customer;
import depot.Customerlist;
import depot.IDFormatException;
import depot.Name;
import depot.NameValueException;

import mvc.Observer;
import mvc.ObserverManager;

public class CustomerThread extends Thread implements Observer{

	private ObserverManager manager_observer;
	private Customerlist customerList;
	private int seq_no;
	
	/** 
	 * this the constructor of CustomerThread
	 * @param manager_observer  it includes all the demanded methods 
	 */
	public CustomerThread(ObserverManager manager_observer){
		this.manager_observer = manager_observer;
	}

	/**
	 * this method is to obtain customerList, and if there is no customers in customerList,
	 * allocate the SeqNo to global variable seq_no
	 */
	public void update() {
		customerList = manager_observer.getAllcustomer();
		if(customerList.getCustomerList().isEmpty())
			seq_no = manager_observer.getSeqNo();
	}
	
	/**
	 * this method is to add new customers into the queue when collection process is running
	 * then the new customers will be processed line by line
	 */
	public void run() {
		update();	
		try {
			File f = new File("NewCustomer");
			Scanner scanner = new Scanner(f);
			while (scanner.hasNextLine()) {
				//read first line and process it
				String inputLine = scanner.nextLine(); 
				if (inputLine.length() != 0) //ignored if blank line
					processLine(inputLine);
			}
			scanner.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
		    }
	}
	
	/**
	 * Processes line, extracts data, creates Customer object
     * and adds to list
     * Checks for non-numeric ID and missing items
	 * Will still crash if name entered without a space
	 * @param line the line to be processed
	 */
	public void processLine(String line) {
		
		try{			
			String parts [] = line.split(",");	
			
			//automated generated the sequence number
				if(!customerList.getCustomerList().isEmpty() ){
					int lastindex = customerList.getCustomerSize()-1;
			    	Customer c = customerList.getCustomerList().get(lastindex);
			    	seq_no = c.getSeqNo()+1;
				}
		    
			Name customername = new Name(parts[0]);
			
			String parcelID = parts[1];			

			Customer c = new Customer(seq_no,customername, parcelID );		
		
			manager_observer.addNewCustomer(c);	
		}
		catch(IDFormatException e)
		{
			System.out.print(e.getMessage());
			}
		catch(ArrayStoreException e)
		{
			System.out.print("The parts"+e.getMessage());
			}
		catch (NameValueException e)
		{
			System.out.print(e.getMessage());
			}
	}
}
